package com.bicon.botu.core.base.common.utils;


import com.bicon.botu.core.base.common.persistence.Node;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author SX
 * Created by SX on 2016/9/28.
 */
public class NodeUtil<T extends Node> {

    private List<T> returnList = new ArrayList<>();

    /**
     * 根据父节点的ID获取所有子节点
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<T> getChildNodes(List<T> list, String parentId) {
        returnList.clear();
        if(list == null && parentId == null) return null;
        assert list != null;
        // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
        list.stream().filter(node -> node.getParentId() == null && Objects.equals(parentId, node.getId())).forEach(node -> {
            recursionFn(list, node);
        });
        return returnList;
    }

    public List<T> getChildNodes(List<T> list ){
        returnList.clear();
        if(list == null ) return null;
        assert list != null;
        // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
//        list.stream().filter(node -> node.getParentId() == null ).forEach(node -> {
        list.stream().filter(node -> "0".equals(node.getParentId()) ).forEach(node -> {
            recursionFn(list, node);
        });
        return returnList;
    }

    private void recursionFn(List<T> list, T node) {
        List<T> childList = getChildList(list, node);// 得到子节点列表
        if (hasChild(list, node)) {// 判断是否有子节点
            node.setChildren(childList);

            for (T n : childList) {
                recursionFn(list, n);
            }
        }/* else {
            returnList.add(node);
        }*/
        if("0".equals(node.getParentId())) {
            returnList.add(node);
        }
    }

    // 得到子节点列表
    private List<T> getChildList(List<T> list, T node) {

        return list.stream().filter(n -> null != n.getParentId() && n.getParentId().equals(node.getId())).collect(Collectors.toList());
    }

    // 判断是否有子节点
    private boolean hasChild(List<T> list, T node) {
        return getChildList(list, node).size() > 0;
    }

}
